using System;
using System.Net;
using System.Net.Sockets;
using Rites.GameObjects;

namespace Rites.Networking
{
    public class ConnectHandler
    {
        private TcpListener listener;

        //When we've received a user, we send an event
        public event UserEventDlg userAdded;

        //Use this to keep track of users we've added, so we can set unique IDs for new connections
        private bool[] idsUsed = new bool[255];

        public ConnectHandler(int portNr)
        {
            this.listener = new TcpListener(IPAddress.Any, portNr);
        }

        ~ConnectHandler()
        {
            this.Stop();
        }

        public void Start()
        {
            this.listener.Start();
            this.ListenForNewClient();
        }

        public void Stop()
        {
            this.listener.Stop();
        }

        private void ListenForNewClient()
        {
            this.listener.BeginAcceptTcpClient(this.AcceptClient, null);
        }

        private void AcceptClient(IAsyncResult ar)
        {
            TcpClient connectedClient = this.listener.EndAcceptTcpClient(ar);

            //Find an empty id
            byte idForNewConnection = 0;

            for (byte i = 0; i < idsUsed.Length; i++)
            {
                if (this.idsUsed[i] == false)
                {
                    idForNewConnection = i;
                    break;
                }
            }
            idsUsed[idForNewConnection] = true;

            //Create a new ArcaComm from the newly connected TcpClient and fire an event
            //to tell everyone else that we've got new client.
            ServerPlayer newPlayer = new ServerPlayer(connectedClient, idForNewConnection);
            newPlayer.UserDisconnected += new UserEventDlg(Player_UserDisconnected);

            if (this.userAdded != null)
                this.userAdded(this, newPlayer);

            this.ListenForNewClient();
        }

        void Player_UserDisconnected(object sender, ServerPlayer player)
        {
            //Reset the id if someone disconnected
            this.idsUsed[player.ID] = false;
        }
    }
}

